#!/bin/bash

# PBJ Server 快速启动脚本

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_header() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}    PBJ Server 快速启动脚本    ${NC}"
    echo -e "${BLUE}================================${NC}"
}

# 检查依赖
check_dependencies() {
    print_message "检查依赖..."
    
    # 检查 Go
    if ! command -v go &> /dev/null; then
        print_error "Go 未安装，请先安装 Go 1.21+"
        exit 1
    fi
    
    # 检查 Go 版本
    GO_VERSION=$(go version | awk '{print $3}' | sed 's/go//')
    REQUIRED_VERSION="1.21"
    
    if [ "$(printf '%s\n' "$REQUIRED_VERSION" "$GO_VERSION" | sort -V | head -n1)" != "$REQUIRED_VERSION" ]; then
        print_error "Go 版本过低，需要 1.21+，当前版本: $GO_VERSION"
        exit 1
    fi
    
    print_message "Go 版本检查通过: $GO_VERSION"
    
    # 检查 MySQL（可选）
    if command -v mysql &> /dev/null; then
        print_message "MySQL 已安装"
    else
        print_warning "MySQL 未安装，请确保数据库服务可用"
    fi
    
    # 检查 Redis（可选）
    if command -v redis-cli &> /dev/null; then
        print_message "Redis 已安装"
    else
        print_warning "Redis 未安装，请确保 Redis 服务可用"
    fi
}

# 安装依赖
install_dependencies() {
    print_message "安装 Go 依赖..."
    go mod download
    go mod tidy
}

# 创建必要的目录
create_directories() {
    print_message "创建必要的目录..."
    mkdir -p logs
    mkdir -p build
    mkdir -p docker/mysql
    mkdir -p docker/nginx/ssl
}

# 检查配置文件
check_config() {
    print_message "检查配置文件..."
    
    if [ ! -f "config/config.yaml" ]; then
        print_error "配置文件 config/config.yaml 不存在"
        exit 1
    fi
    
    print_message "配置文件检查通过"
}

# 构建应用
build_application() {
    print_message "构建应用..."
    
    if [ "$1" = "release" ]; then
        print_message "构建发布版本..."
        CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o build/pbj-server main.go
    else
        print_message "构建开发版本..."
        go build -o build/pbj-server main.go
    fi
    
    print_message "构建完成"
}

# 运行应用
run_application() {
    print_message "启动应用..."
    
    if [ -f "build/pbj-server" ]; then
        ./build/pbj-server
    else
        print_message "使用 go run 启动..."
        go run main.go
    fi
}

# 使用 Docker Compose 启动
start_with_docker() {
    print_message "使用 Docker Compose 启动..."
    
    if ! command -v docker-compose &> /dev/null; then
        print_error "Docker Compose 未安装"
        exit 1
    fi
    
    docker-compose up -d
    print_message "Docker 服务已启动"
    print_message "应用地址: http://localhost:8080"
    print_message "phpMyAdmin: http://localhost:8081"
    print_message "Redis Commander: http://localhost:8082"
}

# 停止 Docker 服务
stop_docker() {
    print_message "停止 Docker 服务..."
    docker-compose down
    print_message "Docker 服务已停止"
}

# 显示帮助信息
show_help() {
    echo "用法: $0 [选项]"
    echo ""
    echo "选项:"
    echo "  build [release]    构建应用 (可选: release 模式)"
    echo "  run                运行应用"
    echo "  dev                开发模式运行"
    echo "  docker-up          使用 Docker Compose 启动"
    echo "  docker-down        停止 Docker 服务"
    echo "  test               运行测试"
    echo "  clean              清理构建文件"
    echo "  help               显示此帮助信息"
    echo ""
    echo "示例:"
    echo "  $0 build           # 构建开发版本"
    echo "  $0 build release   # 构建发布版本"
    echo "  $0 run             # 运行应用"
    echo "  $0 docker-up       # 启动 Docker 服务"
}

# 主函数
main() {
    print_header
    
    case "${1:-help}" in
        "build")
            check_dependencies
            install_dependencies
            create_directories
            check_config
            build_application "$2"
            ;;
        "run")
            check_dependencies
            install_dependencies
            create_directories
            check_config
            run_application
            ;;
        "dev")
            check_dependencies
            install_dependencies
            create_directories
            check_config
            print_message "开发模式启动..."
            go run main.go
            ;;
        "docker-up")
            start_with_docker
            ;;
        "docker-down")
            stop_docker
            ;;
        "test")
            print_message "运行测试..."
            go test -v ./...
            ;;
        "clean")
            print_message "清理构建文件..."
            go clean
            rm -rf build/
            rm -f pbj-server
            rm -f pbj-server.exe
            print_message "清理完成"
            ;;
        "help"|*)
            show_help
            ;;
    esac
}

# 执行主函数
main "$@" 